Exercises
A pure grid
Below, you'll find a customizable two-dimensional grid. In the same application, we're tracking the user's mouse position, and displaying it above the grid.
Your task is to optimize the grid so that it doesn't have to re-render when the user's mouse position changes.
Acceptance Criteria:
Gridshould only re-render when eithernumRowsornumColschanges. Moving the mouse across the viewport should not re-render theGridcomponent.
Code Playground
- Grid render
- Grid render
Solution:
Shopping cart
Let's revisit the “Shopping Cart” exercise back from Module 1!
Update the code so that CartTable doesn't re-render unnecessarily.
Acceptance Criteria:
- Editing the postal code should not trigger a re-render in the
CartTablecomponent.
Code Playground
- CartTable render
- CartTable render
- CartTable render
- CartTable render
Solution:
Memoized clock toggle
In the “Custom Hooks” exercises, we created a handy-dandy useToggle hook:
function useToggle(initialValue = false) { if (typeof initialValue !== 'boolean') { console.warn('Invalid type for useToggle'); }
const [value, setValue] = React.useState( initialValue );
function toggleValue() { setValue((currentValue) => !currentValue); }
return [value, toggleValue];}We've updated our digital clock application to use this hook.
In the sandbox below, you'll find that everything works well... but our ClockToggle component is rendering on every state change, even ones that don't affect it.
Update the code so that ClockToggle doesn't re-render unnecessarily.
Acceptance Criteria:
- The
ClockTogglecomponent should become a pure component ClockToggleshould not re-render when thetimeorshowClockstate variables change.
Code Playground
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
- ClockToggle render
Solution:
Note: I filmed this solution video before Strict Mode was built into the sandbox, and so it only shows one “ClockToggle render” log per tick instead of two. Everything else, however, should be the same regardless.